<template>
	<view class="page">
		<z-paging ref="paging" @scroll="pagScroll">
			<!-- 之后-vue3 -->
			<template #top>
				<uv-navbar :bgColor="'#fff'" autoBack :fixed="false"
					title="添加增减项"></uv-navbar>
			</template>
			<block #refresher="{ refresherStatus }">
				<custom-refresher :status="refresherStatus" />
			</block>
			<!-- 内容 -->
			<view class="content-box">
				<uv-form labelPosition="top" :model="data.formData" :rules="data.rules" ref="form" labelWidth="auto">
					<uv-form-item label="关联项目" prop="xmType.name" required @click="showSelect('xmPicker')">
						<uv-input v-model="data.formData.xmType.name" border="none" readonly placeholder="请选择关联项目" suffixIcon="arrow-right"></uv-input>
					</uv-form-item>
					<!-- 项目信息 -->
					<uv-collapse v-if="data.formData.xmType" :border="false" :value="data.collapse">
						<uv-collapse-item title="项目详情" :clickable="true" name="info">
							<uv-form-item label="项目编号" labelPosition="left">
								<uv-input border="none" readonly >
									<template v-slot:suffix>{{data.formData.xmType.project_number}}</template>
								</uv-input>
							</uv-form-item>
							<uv-form-item label="省市区" labelPosition="left">
								<uv-input border="none" readonly >
									<template v-slot:suffix>{{data.formData.xmType.area}}</template>
								</uv-input>
							</uv-form-item>
							<uv-form-item label="项目品牌" labelPosition="left" >
								<uv-input border="none" readonly >
									<template v-slot:suffix>{{data.formData.xmType.brand_name}}</template>
								</uv-input>
							</uv-form-item>
							<uv-form-item label="项目类型" labelPosition="left" >
								<uv-input border="none" readonly >
									<template v-slot:suffix>{{ projectType(data.formData.xmType.project_type) }}</template>
								</uv-input>
							</uv-form-item>
							<uv-form-item label="报价类型" labelPosition="left" >
								<uv-input border="none" readonly >
									<template v-slot:suffix>
										<span v-if="data.formData.xmType.quotation_type == 1">基础施工报价（首次）</span>
										<span v-if="data.formData.xmType.quotation_type == 2">基础施工报价（调整）</span>
										<span v-if="data.formData.xmType.quotation_type == 3">增减项施工报价</span>
									</template>
								</uv-input>
							</uv-form-item>
							<uv-form-item label="工程经理" labelPosition="left" >
								<uv-input border="none" readonly >
									<template v-slot:suffix>{{data.formData.xmType.engineering_manager_name}}</template>
								</uv-input>
							</uv-form-item>
							<uv-form-item label="报价员" labelPosition="left" >
								<uv-input border="none" readonly >
									<template v-slot:suffix>{{data.formData.xmType.cost_estimator_name}}</template>
								</uv-input>
							</uv-form-item>
						</uv-collapse-item>
					</uv-collapse>
					
					<uv-form-item label="增减项类型" prop="zjxType.name" required @click="showSelect('zjxPicker')">
						<uv-input v-model="data.formData.zjxType.name" border="none" readonly placeholder="请选择增减项类型" suffixIcon="arrow-right"></uv-input>
					</uv-form-item>
					<uv-form-item label="增项预计开工日期" prop="start_date" required v-if="data.formData.zjxType.id == 1"
					  @click="$refs.kgPicker.open()">
					  <uv-input readonly placeholder="请选择增项预计开工日期" border="none" :value="timestampToDateFormat(data.formData.start_date)" suffixIcon="arrow-right"></uv-input>
					</uv-form-item>
					<uv-form-item label="增项预计完工日期" prop="end_date" required v-if="data.formData.zjxType.id == 1"
					  @click="$refs.wgPicker.open()">
					  <uv-input readonly placeholder="请选择增项预计完工日期" border="none" :value="timestampToDateFormat(data.formData.end_date)"
					    suffixIcon="arrow-right"></uv-input>
					</uv-form-item>
					<uv-form-item label="预计工期" prop="day" required v-if="data.formData.zjxType.id == 1">
						<uv-input v-model="data.formData.day" border="none" type="number" readonly  placeholder="等待计算">
							<template v-slot:suffix>天</template>
						</uv-input>
					</uv-form-item>
					<uv-form-item label="增减项原因" prop="yyType.name" required @click="showSelect('yyPicker')">
						<uv-input v-model="data.formData.yyType.name" border="none" readonly placeholder="请选择增减项原因" suffixIcon="arrow-right"></uv-input>
					</uv-form-item>
					<uv-form-item label="增减项内容" prop="nrType.name" required @click="showSelect('nrPicker')">
						<uv-input v-model="data.formData.nrType.name" border="none" readonly placeholder="请选择增减项内容" suffixIcon="arrow-right"></uv-input>
					</uv-form-item>
					<uv-form-item label="施工内容" prop="desc" required>
						<uv-textarea v-model="data.formData.desc" border="none" placeholder="请输入施工内容说明"></uv-textarea>
					</uv-form-item>
					<uv-form-item label="备注" >
						<uv-textarea v-model="data.formData.notes" border="none" placeholder="请输入备注(选填)"></uv-textarea>
					</uv-form-item>
					<uv-form-item>
						<template v-slot:default>
							<view class="form-item-diy" @click="showSelect('fileType')">
								<view class="diy-label">附件</view>
								<uv-icon name="plus-circle"></uv-icon>
							</view>
							<view class="file-item" v-for="(item,idx) in data.formData.fileList" :key="idx">
								<view class="file-name" v-if="item.fileType == 'image'">图片{{idx}}</view>
								<view class="file-name" v-if="item.fileType == 'video'">视频{{idx}}</view>
								<view class="file-name" v-if="item.name">{{item.name}}</view>
								<uv-icon name="close" color="#A4A4A4" @click="delFile(idx)"></uv-icon>
							</view>
						</template>
					</uv-form-item>
				</uv-form>
				<view class="submit_btn ios">
					<uv-button type="primary" text="提交" @click="submit"></uv-button>
				</view>
			</view>
			<view class="ios"></view>
		</z-paging>
		
		<!-- 关联项目 -->
		<uv-picker ref="xmPicker" :columns="data.xmColumns" keyName="name"
			@confirm="pickerConfirm($event,'xmType')"></uv-picker>
		<!-- 增减项类型 -->
		<uv-picker ref="zjxPicker" :columns="data.zjxColumns" keyName="name"
			@confirm="pickerConfirm($event,'zjxType')"></uv-picker>
		<!-- 开工日期 -->
		<uv-datetime-picker ref="kgPicker" :minDate="Date.now()"
			:value="data.formData.start_date ? data.formData.start_date : Date.now()" mode="date"
			@confirm="pickerConfirm($event, 'start_date')"></uv-datetime-picker>
		<!-- 完工日期 -->
		<uv-datetime-picker ref="wgPicker" :minDate="data.formData.start_date ? data.formData.start_date : Date.now()"
			v-model="data.formData.end_date" mode="date"
			@confirm="pickerConfirm($event, 'end_date')"></uv-datetime-picker>
		<!-- 增减项原因 -->
		<uv-picker ref="yyPicker" :columns="data.yyColumns" keyName="name"
			@confirm="pickerConfirm($event,'yyType')"></uv-picker>	
		<!-- 增减项内容 -->
		<uv-picker ref="nrPicker" :columns="data.nrColumns" keyName="name"
			@confirm="pickerConfirm($event,'nrType')"></uv-picker>
		<!-- 附件选择 -->
		<uv-action-sheet ref="fileType" :actions="data.fileType" cancelText="取消" @select="fileTypeChange" round></uv-action-sheet>
	
		<uv-overlay :show="data.loading" opacity="0">
			<view class="overlay-box">
				<view class="loading-box">
					<uv-loading-icon  mode="circle" size="30"></uv-loading-icon>
					<view class="loading-desc">上传中...</view>
				</view>
			</view>
		</uv-overlay>
	</view>
</template>

<script setup>
import {
  array,
  object,
  mobile,
  empty
} from '@/uni_modules/uv-ui-tools/libs/function/test.js';
import {
  reactive,
  getCurrentInstance,
  onMounted,
  computed,
} from 'vue';
import {
  onLoad,
} from '@dcloudio/uni-app';
const {
  proxy: that
} = getCurrentInstance();

onLoad((e) => {
  getProjectList();
});
const data = reactive({
  loading: false,
	collapse: [],
  formData: {
		xmType: '',
		zjxType: '',
		yyType: '',
		start_date: '',
		end_date: '',
		day: '',
		nrType: '',
		desc: '',
		notes: '',
		fileList: [],
  },
  rules: {
		'xmType.name': {
				required: true,
				message: '请选择关联项目',
				trigger: ['blur', 'change']
		},
    'zjxType.name': {
      required: true,
      message: '请选择增减项类型',
      trigger: ['blur', 'change']
    },
		'yyType.name': {
			required: true,
			message: '请选择增减项原因',
			trigger: ['blur', 'change']
		},
		'nrType.name': {
			required: true,
			message: '请选择增减项内容',
			trigger: ['blur', 'change']
		},
		start_date: {
		  validator: (rule, value, callback) => {
		    if (value) {
		      return true;
		    } else {
		      return false;
		    }
		  },
		  required: true,
		  message: '请选择增项预计开工日期',
		  trigger: 'change'
		},
		end_date: {
		  validator: (rule, value, callback) => {
		    if (value) {
		      return true;
		    } else {
		      return false;
		    }
		  },
		  required: true,
		  message: '请选择增项预计完工日期',
		  trigger: 'change'
		},
		desc: {
			required: true,
			message: '请输入施工内容说明',
			trigger: ['change']
		},
  },
  // 附件上传类型
  fileType: [{
	  name: '图片/视频',
	  id: 1
  },{
	  name: '其他文件',
	  id: 2
  }],
  // 关联项目
  xmColumns: [],
  // 增减项类型
  zjxColumns: [[{
    name: '增项',
    id: 1,
  }, {
    name: '减项',
    id: 2,
  }]],
  // 增减项原因
  yyColumns: [[{
	name: '客户原因',
	id: 1,
  },{
	name: '现场原因',
	id: 2,
  },{
	name: '其他',
	id: 3,
  },]],
  // 增减项内容
  nrColumns: [[{
  	name: '顶面工程',
  	id: 1,
  },{
  	name: '地面工程',
  	id: 2,
  },{
  	name: '墙面工程',
  	id: 3,
  },{
  	name: '水电工程',
  	id: 4,
  },{
  	name: '楼梯工程',
  	id: 5,
  },{
  	name: '广告工程',
  	id: 6,
  },{
  	name: '外立面工程',
  	id: 7,
  },{
  	name: '其他工程',
  	id: 8,
  },]],

});

const projectType = computed(() => (type) => {
	let res = '';
	switch (type) {
	  case 1:
		res = '新店'
		break;
	  case 2:
		res = '改造店'
		break;
	  case 3:
		res = '翻新店'
		break;
	  case 4:
		res = '特批新店'
		break;
	  case 5:
		res = '特批改造店'
		break;
	  case 6:
		res = '现场对接店'
		break;
	}
	return res
})

// 打开选项
const showSelect = (type) => {
	if(type == 'xmPicker'){
		if(data.xmColumns[0].length == 0){
			uni.showToast({
				title: '暂无施工中的项目',
				icon: 'none',
				duration: 2000
			});
			return;
		}
		data.collapse = ['info'];
	}
	that.$refs[type].open();
}
// 选项确认
const pickerConfirm = (e, type) => {
  console.log(e)
	if(type == 'start_date'){
		data.formData.start_date = e.value;
		that.$refs.form.validateField('start_date');
		if(e.value > data.formData.end_date){
			data.formData.end_date = '';
			data.formData.day = '';
		}
		if(data.formData.end_date){
			let day = getDaysBetweenDates(data.formData.start_date, data.formData.end_date)
			data.formData.day = day + 1;
		}
		return;
	}else if(type == 'end_date'){
		data.formData.end_date = e.value;
		that.$refs.form.validateField('end_date');
		let day = getDaysBetweenDates(data.formData.start_date, data.formData.end_date)
		data.formData.day = day + 1;
		return;
	}
  data.formData[type] = e.value[0];
  that.$refs.form.validateField(`${type}.name`);
}
function getDaysBetweenDates(date1, date2) {
	// 将日期字符串转换为时间戳
	var timestamp1 = new Date(date1).getTime();
	var timestamp2 = new Date(date2).getTime();

	// 计算两个时间戳之间的天数
	var days = Math.ceil(Math.abs(timestamp2 - timestamp1) / (1000 * 3600 * 24));

	return days;
}
// 附件类型确认
const fileTypeChange = (e) => {
	if(e.id == 1){
		uni.chooseMedia({
			mediaType: ['image','video'],
			sourceType: ['album', 'camera'],
			maxDuration: 30,
			success(res) {
				console.log(res.tempFiles);
				res.tempFiles.map(item => {
					data.formData.fileList.push(item)
				})
			}
		})
	}else{
		wx.chooseMessageFile({
			count: 9,//限制选择的文件数量
			type: 'file',//非图片和视频的文件,不选默认为all
			success (res) {
				console.log(res.tempFiles, data)
				res.tempFiles.map(item => {
					data.formData.fileList.push(item)
				})
			}
		})
	}
}
const delFile = (idx) => {
	data.formData.fileList.splice(idx, 1);
}
// 提交
const submit = () => {
// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
	that.$refs.form.validate().then((res) => {
		console.log(data.formData)
		uni.showLoading({
			mask: true,
			title: '信息提交中...'
		});
		if(data.formData.fileList.length == 0 ){
			wxApplyChangeItems({arrResult: []});
			return;
		}
		that.$upload(data.formData.fileList).then((res) => {
			console.log(1111, res);
			wxApplyChangeItems(res);
		}).catch((err) => {
			uni.hideLoading();
		})
		
	}).catch((errors) => { });
}
const wxApplyChangeItems = (res) => {
	let formData = data.formData;
	that.$hApi.wxApplyChangeItems({
		project_id: formData.xmType.id,
		increase_or_decrease: formData.zjxType.id,
		start_date: formData.start_date,
		end_date: formData.end_date,
		expect_duration_days: formData.day,
		reason_type: formData.yyType.id,
		change_content: formData.nrType.id,
		construction_content: formData.desc,
		remark: formData.notes,
		change_items_file: res.arrResult,
	}).then(res => {
		console.log(res, 'wxApplyChangeItems');
		uni.hideLoading();
		if (res.code == 200) {
			setTimeout(() => {
				uni.navigateBack();
			}, 300)
		}
		uni.showToast({
			title: res.code == 200 ? '操作成功' : res.message,
			icon: res.code == 200 ? 'success' : 'error'
		});
	}).catch((err) => {
		uni.hideLoading();
	})
}
function timestampToDateFormat(timestamp) {
  if (!timestamp) return '';
  const dateObj = new Date(timestamp); // 创建Date对象
  const year = String(dateObj.getFullYear()); // 获取年份
  const month = String(dateObj.getMonth() + 1).padStart(2, '0'); // 获取月份，并补零
  const day = String(dateObj.getDate()).padStart(2, '0'); // 获取日期，并补零

  return year + '-' + month + '-' + day; // 返回转换后的日期格式
}
// api
const getProjectList = () => {
	that.$hApi.allowAssociatedProjects({}).then(res => {
	    console.log(res, '项目列表')
	    if (res.code == 200) {
			res.data.map(item => {
				item.name = item.project_name;
			})
			data.xmColumns = [res.data];
	    }
	})
}

</script>

<style lang="scss" scoped>
	@import './index.scss';
</style>